package com.szr.leex.po.generator;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import com.szr.leex.po.id.StringIdentityEntity;

/**
 * string type generator to generate UUID
 * Created by WangChen on 2018/9/11 22:19.
 */
public class StringGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        Serializable serializable=org.hibernate.id.UUIDGenerator.buildSessionFactoryUniqueIdentifierGenerator().generate(session, object);
        String uuid = serializable.toString().replaceAll("-","");
        if(object != null && (object instanceof StringIdentityEntity)){
            StringIdentityEntity entity = (StringIdentityEntity) object;
            return isBlank(entity.getId()) ? uuid : entity.getId();
        }
        return uuid;
    }

    private boolean isBlank(String str){
        if(str == null || str.trim().length() == 0) {
            return true;
        }
        return false;
    }
}
